import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/login/suc_return_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/routes.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';

import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';

/// 我的页面金刚区
class MyTabWidget extends StatelessWidget {
  /// 标题
  final String title;
  final bool showBackground;

  /// 相关内容展示
  final List<Map<String, dynamic>> tabList;

  /// 游客登录后刷新相关页面
  final Function() ykdlFun;

  final Color backgroundColor;

  const MyTabWidget({
    super.key,
    required this.title,
    required this.tabList,
    required this.ykdlFun,
    this.showBackground = false,
    this.backgroundColor = colorGrey4,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 30),
      decoration: BoxDecoration(
        color: colorWhite1,
        borderRadius: BorderRadius.all(Radius.circular(16)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _title(),
          _content(context),
        ],
      ),
    );
  }

  /// 显示标题
  _title() {
    return Padding(
      padding: EdgeInsets.only(left: 20, top: 24),
      child: Text(
        title,
        style: FontUtil.fontBlack1(18, fontWeight: FontWeight.w500),
      ),
    );
  }

  /// 显示内容
  _content(BuildContext context) {
    // 计算显示的小组件显示的宽度
    double width = ScreenUtil().screenWidth;
    double itemWidth = (width - 60) / 4;
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 30),
      child: Wrap(
        runSpacing: 30,
        children: tabList.map((Map<String, dynamic> map) {
          return _tabItem(map, itemWidth, context);
        }).toList(),
      ),
    );
  }

  /// 内容tab显示方法
  Widget _tabItem(
      Map<String, dynamic> map,
      double itemWidth,
      BuildContext context,
      ) {
    return GestureDetector(
      onTap: () {
        _onTapFun(map, context);
      },
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        width: itemWidth,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if(showBackground)
              Container(
                decoration: BoxDecoration(
                  color: backgroundColor,
                  borderRadius: BorderRadius.all(Radius.circular(15.w)),
                ),
                padding: EdgeInsets.all(5.w),
                child: map.containsKey("pngUrl")?Image.asset(map["pngUrl"],
                  width: 20.w,
                  height: 20.w,):SvgPicture.asset(
                  map["svgUrl"],
                  width: 20.w,
                  height: 20.w,
                ),
              ) else if(map.containsKey("svgUrl")) SvgPicture.asset(
              map["svgUrl"],
              // width: px44,
              // height: px44,
              width: 20.w,
              height: 20.w,
            )else Image.asset(map["pngUrl"],
              width: 20.w,
              height: 20.w,),
            hiSpace(height: 20),
            Text(
              map["name"],
              style: FontUtil.fontBlack1(14),
            )
          ],
        ),
      ),
    );
  }

  /// 点击方法
  _onTapFun(Map<String, dynamic> map, BuildContext context) {
    var name = map["pageName"];
    if (name != null) {
      if(isNeedLogin(name)){
        Navigator.pushNamed(context, "/login");
      }else{
        Navigator.pushNamed(context, name);
      }
    } else {
      if (map["name"] == "清空做题记录") {
        if (dataUtilComm.dataModel.visitorsType) {
          // 跳转登录页
          Navigator.pushNamed(context, "/login",arguments: {
            "closeVisitors": false,
            "sucReturn": SucReturnEnum.ret,
          }).then((value) {
              if (value == true) {
                ykdlFun();
                _cleanCategoryFun(context);
              }
            });

        } else {
          _cleanCategoryFun(context);
        }
      }
    }
  }

  /// 清除做题记录方法
  _cleanCategoryFun(BuildContext context) {
    // 打开弹框询问
    ToastUtil.showDialogBox(
      context: context,
      contentText: "清除科目下所有做题记录，该操作不可撤回。是否清除？",
      contentStyle: FontUtil.fontRed2(30, fontWeight: FontWeight.w500),
      btnLeftText: "取消",
      btnLeftTextColor: colorGrey2,
      btnRightText: "确定",
      btnRightBackgroundColor: colorRed2,
    ).then((bool? value) {
      if (value != null && value) {
        // 打开加载框
        ToastUtil.loadingBoxShow(context);
        // 加载相关方法
        DataModel dataModel = dataUtilComm.dataModel;
        MyDao.cleanCategory(
          industryCode: dataModel.industryId,
          examId: dataModel.examId,
          categoryId: dataModel.categoryId,
        ).then((bool res) {
          // 关闭加载框
          ToastUtil.loadingBoxRemove();
          // 提示
          ToastUtil.show(context: context, msg: res ? "清除成功" : "清除失败");
        }).catchError((e) {
          // 关闭加载框
          ToastUtil.loadingBoxRemove();
          String msg = "未知错误，请重试";
          if (e is DaoException) {
            msg = e.msg;
          }
          ToastUtil.show(context: context, msg: msg);
        });
      }
    });
  }
}
